const app = require('./app');
const logger = require('./utils/logger');
const blockchainService = require('./services/blockchainService');

const PORT = process.env.PORT || 3000;

const server = app.listen(PORT, async () => {
  logger.info(`🚀 服务器运行在端口 ${PORT}`);
  logger.info(`🌍 API文档地址: http://localhost:${PORT}/api/v1`);
  logger.info(`🏥 健康检查地址: http://localhost:${PORT}/api/v1/health`);
  logger.info(`📊 环境: ${process.env.NODE_ENV || 'development'}`);
  
  // 初始化区块链服务
  try {
    await blockchainService.initialize();
    if (blockchainService.isAvailable()) {
      logger.info('🔗 区块链服务已连接');
    } else {
      logger.warn('⚠️  区块链服务不可用，系统将在非区块链模式下运行');
    }
  } catch (error) {
    logger.error('区块链服务初始化失败:', error.message);
  }
});

// 优雅关闭处理
const gracefulShutdown = (signal) => {
  logger.info(`收到 ${signal} 信号，开始优雅关闭服务器...`);
  
  server.close((err) => {
    if (err) {
      logger.error('服务器关闭时发生错误:', err);
      process.exit(1);
    }
    
    logger.info('服务器已优雅关闭');
    process.exit(0);
  });
  
  // 如果30秒内没有关闭，强制退出
  setTimeout(() => {
    logger.error('强制关闭服务器');
    process.exit(1);
  }, 30000);
};

process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));

// 未捕获异常处理
process.on('uncaughtException', (err) => {
  logger.error('未捕获的异常:', {
    error: err.message,
    stack: err.stack
  });
  process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
  logger.error('未处理的Promise拒绝:', {
    reason: reason,
    promise: promise
  });
  process.exit(1);
});

module.exports = server;